//条件变量使用
#include <vector>
#include <pthread.h>
#include <string>
#include <iostream>
#include <unistd.h>

#define NUM 5
int cnt = 0;

pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* threadrun(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&glock);
        pthread_cond_wait(&gcond,&glock);//在条件变量中等待的线程一旦全部醒来都会先去竞争锁
        //但只有一个会竞争成功，然后才申请条件变量，如果只唤醒一个线程,那就会唤醒在条件变量下等的线程
        std::cout << name << "计算 cnt:" << cnt << std::endl;
        pthread_mutex_unlock(&glock);
        cnt++;
        // usleep(123);
    }
}

int main()
{
    std::vector<pthread_t> threads;
    for(int i = 0;i < NUM ;i++)
    {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name,64,"thread-%d",i+1);
        int n = pthread_create(&tid,nullptr,threadrun,name);
        if(n != 0)
            continue;
        threads.push_back(tid);
    }

    sleep(3);

    while(true)
    {
        std::cout << "唤醒所有线程" << std::endl;
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for(auto thread:threads)
    {
        int m = pthread_join(thread,nullptr);
        (void)m;
    }

    return 0;
}